const express = require('express');
const mysql = require('mysql2/promise');
const { nanoid } = require('nanoid');
const AWS = require('aws-sdk');
const axios = require('axios');

const app = express();
const port = 3000;

// 配置数据库连接
const pool = mysql.createPool({
  host: process.env.TIDB_HOST,
  port: process.env.TIDB_PORT,
  user: process.env.TIDB_USER,
  password: process.env.TIDB_PASSWORD,
  database: process.env.TIDB_DATABASE,
  ssl: {
    rejectUnauthorized: true
  }
});

// 配置OSS
const oss = new AWS.S3({
  endpoint: process.env.OSS_ENDPOINT,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  secretAccessKey: process.env.OSS_SECRET_ACCESS_KEY,
  signatureVersion: 'v4',
  region: process.env.OSS_REGION
});

// 配置AI服务
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 健康检查
app.get('/api/health', (req, res) => {
  res.send('OK');
});

// 获取上传URL
app.get('/api/upload-url', async (req, res) => {
  try {
    const { filename, contentType } = req.query;
    const fileKey = `reviews/${nanoid()}-${filename}`;
    
    const params = {
      Bucket: process.env.OSS_BUCKET,
      Key: fileKey,
      Expires: 300, // 5分钟有效期
      ContentType: contentType
    };
    
    const uploadUrl = oss.getSignedUrl('putObject', params);
    
    res.json({
      uploadUrl,
      fileKey
    });
  } catch (error) {
    console.error('获取上传URL失败:', error);
    res.status(500).json({ error: '获取上传URL失败' });
  }
});

// 提交评价
app.post('/api/reviews', async (req, res) => {
  const connection = await pool.getConnection();
  
  try {
    await connection.beginTransaction();
    
    const { 
      userId, 
      userName, 
      restaurantName, 
      restaurantLocation, 
      dishName, 
      rating, 
      reviewText, 
      imageKeys 
    } = req.body;
    
    // 1. 查找或创建用户
    let [users] = await connection.execute(
      'SELECT id FROM users WHERE user_id = ?',
      [userId]
    );
    
    let user;
    if (users.length === 0) {
      const [result] = await connection.execute(
        'INSERT INTO users (user_id, user_name) VALUES (?, ?)',
        [userId, userName || null]
      );
      user = { id: result.insertId };
    } else {
      user = users[0];
    }
    
    // 2. 查找或创建餐厅
    let [restaurants] = await connection.execute(
      'SELECT id FROM restaurants WHERE name = ? AND location = ?',
      [restaurantName, restaurantLocation]
    );
    
    let restaurant;
    if (restaurants.length === 0) {
      const [result] = await connection.execute(
        'INSERT INTO restaurants (name, location) VALUES (?, ?)',
        [restaurantName, restaurantLocation]
      );
      restaurant = { id: result.insertId };
    } else {
      restaurant = restaurants[0];
    }
    
    // 3. 分析评价情感
    let sentimentScore = null;
    if (reviewText && OPENAI_API_KEY) {
      try {
        const response = await axios.post(
          'https://api.openai.com/v1/chat/completions',
          {
            model: 'gpt-3.5-turbo',
            messages: [
              {
                role: 'user',
                content: `请分析以下文本的情感倾向，返回一个-1到1之间的数值，-1表示非常负面，1表示非常正面："${reviewText}"`
              }
            ],
            temperature: 0
          },
          {
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${OPENAI_API_KEY}`
            }
          }
        );
        
        // 提取情感分数
        const scoreText = response.data.choices[0].message.content.trim();
        sentimentScore = parseFloat(scoreText);
        
        // 确保分数在有效范围内
        if (isNaN(sentimentScore) || sentimentScore < -1 || sentimentScore > 1) {
          sentimentScore = null;
        }
      } catch (error) {
        console.error('情感分析失败:', error);
        sentimentScore = null;
      }
    }
    
    // 4. 创建评价
    const [reviewResult] = await connection.execute(
      'INSERT INTO reviews (user_id, restaurant_id, dish_name, rating, review_text, sentiment_score) VALUES (?, ?, ?, ?, ?, ?)',
      [user.id, restaurant.id, dishName || null, rating, reviewText, sentimentScore]
    );
    
    const reviewId = reviewResult.insertId;
    
    // 5. 保存图片信息
    if (imageKeys && imageKeys.length > 0) {
      const ossBaseUrl = process.env.OSS_PUBLIC_URL;
      
      const imageValues = imageKeys.map(key => [
        reviewId,
        key,
        `${ossBaseUrl}/${key}`
      ]);
      
      await connection.execute(
        'INSERT INTO review_images (review_id, file_key, url) VALUES ?',
        [imageValues]
      );
    }
    
    await connection.commit();
    
    res.json({
      id: reviewId,
      message: '评价提交成功'
    });
  } catch (error) {
    await connection.rollback();
    console.error('提交评价失败:', error);
    res.status(500).json({ error: '提交评价失败' });
  } finally {
    connection.release();
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在端口 ${port}`);
});